
% concatenates two arrays along arbitrary dimension 
function r = nancat2(a,b,dim)

asz = size(a);
bsz = size(b);

for n = 1:max(ndims(a),ndims(a))
    if n == dim
        continue;
    end
    if ndims(a) < n
        a = cat(n,a,nan(size(a)));
    elseif ndims(b) < n
        b = cat(n,b,nan(size(b)));
    end
    if size(a,n) < size(b,n)
        cursz = size(a);
        cursz(n) = size(b,n)-size(a,n);
        temp  = nan(cursz);
        a = cat(n,a,temp);
    elseif size(b,n) < size(a,n)
        cursz = size(b);
        cursz(n) = size(a,n)-size(b,n);
        temp  = nan(cursz);
        b = cat(n,b,temp);
    end
end
r = cat(dim,a,b);